import axios, { AxiosRequestConfig, AxiosResponse } from 'axios';

const server = axios.create({
  baseURL: 'http://localhost:3333',
  headers: {
    'Content-Type': 'application/json'
  },
  timeout: 5000 // 5s没有响应就报错
});

// 请求的拦截器
server.interceptors.request.use((config: AxiosRequestConfig<any>) => {
  if (config.headers != null) {
    // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
    config.headers.Authorization = `Bearer ${localStorage.getItem('token')}`;
  }
  return config;
});

server.interceptors.response.use((response: AxiosResponse<any>) => {
  return response.data;
}
, (error: any) => {
  // 未授权
  if (error.response.status === 401) {
    // 跳转到登录页
    // router.push('/login');
  }
  return error;
});

export default server;
